import { Component, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { merge, tap } from 'rxjs';
@Component({
  selector: 'app-community',
  templateUrl: './community.component.html',
  styleUrls: ['./community.component.scss']
})
export class CommunityComponent {
  dataSource:any[]=[]
  /**
   * @example
   * [length]="dataSource_length"
   * 双向绑定，定义数据的数量的长度
   */
  dataSource_length=data.length
  
  /**
   *  直接指定 MatPaginator 分页组件类
   */
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  /**
   * 选取数组中下标大于等于0小于5的值，并返回一个新数组
   */
  //第一次显示数据绑定和设置指令/组件的输入属性之后，初始化指令/组件
  ngOnInit(){
    this.dataSource=data.slice(0,5)
  }
  /**
   * 将数组displayedColumns 中的值一次分配给 colum
   * @example
   * <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
   * 
   */
  displayedColumns: string[] = ['position', 'name', 'weight',];

  //ngAfterViewInit() 初始化完组件视图及其子视图之后调用
  ngAfterViewInit(): void {
    merge(this.paginator.page)
      .pipe(
        tap(() => this.next_page())
      )
      .subscribe();
  }
  //翻页操作
  next_page(): void {
    /**
     * this.paginator.pageIndex 当前页面索引
     * this.paginator.pageSize  表格显示的行数
     */
    this.dataSource=data.slice(this.paginator.pageIndex*this.paginator.pageSize,this.paginator.pageIndex*this.paginator.pageSize+this.paginator.pageSize)
  }
}
const data= [
  { position: 1, name: 'Hydrogen', weight: 1.0079, },
  { position: 2, name: 'Helium', weight: 4.0026,  },
  { position: 3, name: 'Lithium', weight: 6.941,  },
  { position: 4, name: 'Beryllium', weight: 9.0122,  },
  { position: 5, name: 'Boron', weight: 10.811,  },
  { position: 6, name: 'Carbon', weight: 12.0107,  },
  { position: 7, name: 'Nitrogen', weight: 14.0067, },
  { position: 8, name: 'Oxygen', weight: 15.9994,  },
  { position: 9, name: 'Fluorine', weight: 18.9984,  },
  { position: 10, name: 'Neon', weight: 20.1797,  },
  { position: 11, name: 'Sodium', weight: 22.9897,  },
  { position: 12, name: 'Magnesium', weight: 24.305, },
  { position: 13, name: 'Aluminum', weight: 26.9815,  },
  { position: 14, name: 'Silicon', weight: 28.0855,  },
  { position: 15, name: 'Phosphorus', weight: 30.9738,  },
  { position: 16, name: 'Sulfur', weight: 32.065,  },
  { position: 17, name: 'Chlorine', weight: 35.453,  },
  { position: 18, name: 'Argon', weight: 39.948,  },
  { position: 19, name: 'Potassium', weight: 39.0983,  },
  { position: 20, name: 'Calcium', weight: 40.078,  },
];
